const sharp = require('sharp');
const fs = require('fs/promises');
const path = require('path');

async function compressWithoutFormatChange(inputDir, outputDir, options = {}) {
  // 检查输入目录是否存在
  try {
    await fs.access(inputDir);
  } catch (error) {
    console.error(`输入目录不存在: ${inputDir}`);
    return; // 退出函数
  }

  const files = await fs.readdir(inputDir);
  
  await Promise.all(files.map(async (file) => {
    const ext = path.extname(file).toLowerCase();
    const inputPath = path.join(inputDir, file);
    const outputPath = path.join(outputDir, file);

    // 根据格式应用不同压缩策略
    const processor = sharp(inputPath)
      .rotate() // 自动修正方向
      .withMetadata({ orientation: undefined }); // 移除方向元数据

    // 确保质量参数在 0 到 100 之间
    const quality = Math.min(Math.max(options.quality || 85, 0), 100);
    console.log(`Processing ${file}: quality = ${quality}`); // 调试信息

    switch(ext) {
      case '.jpg':
      case '.jpeg':
        await processor.jpeg({ 
          quality: quality,
          mozjpeg: true // 启用高级压缩算法
        }).toFile(outputPath);
        break;
      case '.png':
        await processor.png({
          quality: quality ? quality * 1 : 80, // 百分比转10级
          compressionLevel: 9, // 最高压缩级别
          adaptiveFiltering: true
        }).toFile(outputPath);
        break;
      case '.webp':
        await processor.webp({ 
          quality: quality,
          effort: 6 // 最高压缩努力级别
        }).toFile(outputPath);
        break;
      default:
        console.warn(`不支持的文件格式: ${ext}`);
    }
  }));
}


// 新增压缩单个图片的函数
async function compressSingleImage(inputPath, outputPath, options = {}) {
  const ext = path.extname(inputPath).toLowerCase();
  const processor = sharp(inputPath)
    .rotate()
    .withMetadata({ orientation: undefined });

  // 确保质量参数在 0 到 100 之间
  const quality = Math.min(Math.max(options.quality || 85, 0), 100);
  console.log(`Compressing single image: quality = ${quality}`); // 调试信息

  switch(ext) {
    case '.jpg':
    case '.jpeg':
      await processor.jpeg({ 
        quality: quality,
        mozjpeg: true
      }).toFile(outputPath);
      break;
    case '.png':
      await processor.png({
        quality: quality ? quality * 1 : 80,
        compressionLevel: 9,
        adaptiveFiltering: true
      }).toFile(outputPath);
      break;
    case '.webp':
      await processor.webp({ 
        quality: quality,
        effort: 6
      }).toFile(outputPath);
      break;
    default:

      console.warn(`不支持的文件格式: ${ext}`);
  }
}

// 使用示例：压缩单个图片
compressSingleImage('../imgchange/icon1.png', './imgchange/icon1.png', { quality: 80 });